//
//  SPBaseViewController.m
//  SmartCity
//
//  Created by LSP on 2017/5/12.
//  Copyright © 2017年 NRH. All rights reserved.
//

#import "SPBaseViewController.h"
#import <SPFoundationCategory/SPFoundationCategory.h>
#import "SPNavigationController.h"

NSString * const SPBaseViewControllerRefreshSourceVCKey = @"SPBaseViewControllerRefreshSourceVCKey";
NSString * const SPBaseViewControllerRefreshChangedObjectKey = @"SPBaseViewControllerRefreshChangedObjectKey"; 

@interface SPBaseViewController () <UINavigationControllerDelegate>

@end

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wincomplete-implementation"
@implementation SPBaseViewController
#pragma clang diagnostic pop

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
#if DEBUG
    NSLog(@"-[%@ dealloc]", [self class]);
#endif
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupSubviews];
    
    if ([self respondsToSelector:@selector(setupNavigationItems)]) {
        [self setupNavigationItems];
    }
    
    if ([self respondsToSelector:@selector(initialization)]) {
        [self initialization];
    }
    
    if (self.navigationController.interactivePopGestureRecognizer.delegate != self.navigationController) {
        
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    
    [self _sp_registerNotifications];
    
    if (!self.view.backgroundColor) {
        self.view.backgroundColor = [UIColor whiteColor];
    }
    
#ifdef __IPHONE_11_0
    if (@available(iOS 11.0, *)) {
        SEL selector = NULL;
        
        NSArray *selNames = @[@"scrollView", @"tableView", @"collectionView"];
        
        for (NSString *selName in selNames) {
            selector = NSSelectorFromString(selName);
            
            UIScrollView *scrollView = nil;
            if ([self respondsToSelector:selector]) {
                scrollView = [self performSelector:selector];
            }
            if (scrollView) {
                scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
                
                if ([selName isEqualToString:@"tableView"]) {
                    UITableView *tableView = (id)scrollView;
                    
                    tableView.estimatedRowHeight = 0;
                    tableView.estimatedSectionHeaderHeight = 0;
                    tableView.estimatedSectionFooterHeight = 0;
                }
            }
        }
        
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
#endif
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer == self.navigationController.interactivePopGestureRecognizer) {
        return self.navigationController.viewControllers.count > 1;
    }
    return YES;
}

- (void)_sp_registerNotifications {
    NSNotificationCenter *nfc = [NSNotificationCenter defaultCenter];
    [nfc addObserver:self
                                             selector:@selector(refreshHandle:)
                                                 name:NSStringFromClass([self class])
                                               object:nil];
//    [nfc addObserver:self
//                                             selector:@selector(loginSuccessHandle:)
//                                                 name:PPUserDidLoginSignInNotification
//                                               object:nil];
//    [nfc addObserver:self
//                                             selector:@selector(showLoginView)
//                                                 name:PPUserDidLoginSignUpNotification
//                                               object:nil];
//    [nfc addObserver:self
//            selector:@selector(userDidLogout)
//                name:PPUserDidLoginSignUpNotification
//              object:nil];
}

- (void)pushViewController:(UIViewController *)viewController
{
    if (!viewController) {
        return;
    }
    
    if (!self.navigationController) {
#if 1
        UINavigationController *navi;
        if ([viewController isKindOfClass:[SPBaseViewController class]]) {
            navi = [[SPNavigationController alloc] initWithRootViewController:viewController];
        }else{
            navi = [[UINavigationController alloc] initWithRootViewController:viewController];
        }
//        [self wxs_presentViewController:navi animationType:(WXSTransitionAnimationTypeSysPushFromRight) completion:nil];
        [self presentViewController:navi animated:YES completion:nil];
#else
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:viewController];
        [self presentViewController:navi animated:YES completion:nil];
#endif
        return;
    }
    
    // 防止连续被导航栏控制器推出, 如需要连续推出, 请实现-(BOOL)canSerialPush 并返回YES.
    if ([viewController isKindOfClass:[self.navigationController.viewControllers.lastObject class]]) {
        if ([viewController isKindOfClass:[SPBaseViewController class]]) {
            if(![(SPBaseViewController *)viewController canSerialPush]) {
                return;
            }
        }else if ([viewController respondsToSelector:@selector(canSerialPush)]) {
            if(![(id)viewController canSerialPush]) {
                return;
            }
        }else{
            return;
        }
    }
    
#if 1
    if ([self.navigationController isKindOfClass:[SPNavigationController class]]) {
        [(SPNavigationController *)self.navigationController pushViewController:viewController];
    }else{
        [self.navigationController pushViewController:viewController animated:YES];
    }
#else
    [self presentViewController:viewController animated:YES completion:nil];
#endif
}


- (void)backViewController {
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count == 1) {
            if (self.navigationController.presentingViewController) {
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            }
        }else if (self.navigationController.viewControllers.count == 2) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else if (self.navigationController.viewControllers.count > 2) {
            UIViewController *pre = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 2];
            [self.navigationController popToViewController:pre animated:YES];
        }
    }else if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)showLoginView {
    if (self.view.window) {
        [self gotoLoginAndSuccessCallback:nil];
    }
}

- (void)userDidLogout {
    // 供子类
}

- (void)gotoLoginAndSuccessCallback:(void (^)())success {
//    [[UIApplication sharedApplication].keyWindow switchRootController];
//    HTLoginViewController *vc = [HTLoginViewController loginViewController];
//    vc.loginSuccessCallBack = success;
//    
//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
//    [self presentViewController:nav animated:YES completion:nil];
    
}
- (BOOL)ensureHadLoginIfFailed:(void(^)())failureContinue {
//    if ([PPUserDefaults boolForKey:PPUserDefaultIsLogin]) {
//        return YES;
//    }
//    [self gotoLoginAndSuccessCallback:failureContinue];
    return NO;
}
- (void)ensureHadLoginExecute:(void (^)(void))execute {
    if ([self ensureHadLoginIfFailed:execute]) {
        execute();
    }
}

- (void)refreshViewControllerWithName:(NSString *)vcName {
    [self refreshViewControllerWithName:vcName userinfo:nil];
}
- (void)refreshViewControllerWithName:(NSString *)vcName userinfo:(NSDictionary *)userinfo {
    if (![vcName isValidString]) {
        return;
    }
    NSNotification *notification = [NSNotification notificationWithName:vcName object:nil userInfo:userinfo];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)refreshHandle:(NSNotification *)notification {
    if ([self isViewLoaded]) {
        [self refreshContent:notification];
    }
}
- (void)refreshContent:(NSNotification *)notification {
    // 供子类实现.
#if DEBUG
    NSLog(@"Hanlde a notification for %@, you need override %s to refresh your content.", [self class], _cmd);
#endif
}

- (void)loginSuccessHandle:(NSNotification *)notification {
    if ([self isViewLoaded]) {
        [self loginSuccessNotification:notification];
    }
}
- (void)loginSuccessNotification:(NSNotification *)notification {
    
}

#if DEBUG
- (void)setupSubviews {
    NSLog(@"%@:子类 -> %@ 重载方法错误. %@", @"SPBaseViewController", NSStringFromClass([self class]), @"***子类需重载此方法，且无需调用 [super setupSubviews]。***");
}
#else
- (void)setupSubviews {
    // ***子类需重载此方法，且无需调用 [super setupSubviews]。
}
#endif

//- (void)navigationController:(UINavigationController *)navigationController
//      willShowViewController:(UIViewController *)viewController
//                    animated:(BOOL)animated {
//    
//}
//- (void)navigationController:(UINavigationController *)navigationController
//       didShowViewController:(UIViewController *)viewController
//                    animated:(BOOL)animated {
//    
//}

- (BOOL)canSerialPush {
    // 子类可重载
    return NO;
}

- (void)callPhone:(NSString *)phone {
    if (!phone.isValidString) {
        return;
    }
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"TEL://%@", phone]]];
}

@end


#if DEBUG

#import <objc/runtime.h>

@interface UIViewController (AppearLog)

@end

@implementation UIViewController (AppearLog)

+ (void)load{
    NSArray *originalSelectors = @[@"viewDidAppear:"];
    
    for (NSString *selectorName in originalSelectors) {
        SEL originalSelector = NSSelectorFromString(selectorName);
        SEL swizzledSelector = NSSelectorFromString([@"sp_" stringByAppendingString:selectorName]);
        
        Method originalMethod = class_getInstanceMethod(self, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
        
        BOOL didAddMethod =
        class_addMethod(self,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(self,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
            
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    }
}


- (void)sp_viewDidAppear:(BOOL)animated {
    NSNumber *_firstAppear = objc_getAssociatedObject(self, _cmd);
    if (!_firstAppear.boolValue) {
        objc_setAssociatedObject(self, _cmd, @YES, OBJC_ASSOCIATION_COPY_NONATOMIC);
        
        NSLog(@"-[%@ firstAppear]", [self class]);
    }
    return [self sp_viewDidAppear:animated];
}

@end

#endif
